import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, TreeSelect, Popconfirm, Table } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { queryRule, updateRule, addRule, removeRule, getDictionary } from './service';
import styles from '../../../global.less';
import FormItem from 'antd/lib/form/FormItem';
import { transTitle } from '@/utils/utils';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [secondData, setSecondData] = useState([]);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [parent, setParent] = useState();
  const [menuValues, setMenuValues] = useState();
  const [count, setCount] = useState('');
  const [tableData, setTableData] = useState([]);
  const [rowKey, setRowKey] = useState([]);
  const [childrenRowKey, setChildrenRowKey] = useState([]);
  const [children, setChildren] = useState([]);
  const ListOnChange = (value) => {
    setParent(value);
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '所属模块',
      dataIndex: 'module',
      valueType: 'text',
    },
    {
      title: '键',
      dataIndex: 'key',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '值',
      dataIndex: 'value',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      valueType: 'text',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              labelInValue
              value={parent}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={ListOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            {' '}
            <a
              onClick={() => {
                handleUpdateModalVisible(true);
                handleModalVisible(true);
                setStepFormValues(record);
                return record.module === 'area'
                  ? (transTitle(tableData), setMenuValues(tableData))
                  : setMenuValues(secondData);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="Yes"
              cancelText="No"
            >
              <a onClick={() => {}}>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  const getChildren = (payload) => {
    const module =
      payload.module == 'province' ? 'city' : payload.module == 'city' ? 'area' : 'system';
    getDictionary(module, payload.id).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        if (data.length > 0) {
          if (module === 'city') {
            data.map((item) => {
              return (item.children = []);
            });
            setTableData(data);
          } else if (module === 'system') {
            return setTableData(data);
          } else {
            let newTable = JSON.parse(JSON.stringify(tableData));
            if (newTable.length > 0) {
              const num = newTable.findIndex((item) => {
                return item.id === payload.id;
              });
              newTable[num].children = data;
              return setTableData(newTable);
            }
          }
        } else {
          return setTableData(data);
        }
      }
    });
  };
  const TableArea = () => {
    return (
      <Table
        columns={columns}
        headerTitle={false}
        search={false}
        rowKey="id"
        options={false}
        dataSource={children}
        pagination={false}
      />
    );
  };
  const expandedRowRender = () => {
    return (
      <ProTable
        columns={columns}
        headerTitle={false}
        rowKey="id"
        bordered
        search={false}
        options={false}
        dataSource={tableData}
        pagination={false}
        expandedRowKeys={childrenRowKey}
        onExpand={(e, payload) => {
          setChildrenRowKey([payload.id]);
          if (!e) return setChildrenRowKey([]);
          getChildren(payload);
        }}
        expandable={{ TableArea }}
      />
    );
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="数据字典"
        actionRef={actionRef}
        rowKey="id"
        bordered
        scroll={{x:1200}}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
              handleUpdateModalVisible(false);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          const data = JSON.parse(JSON.stringify(list));
          transTitle(data);
          setSecondData(data);
          setMenuValues(data);
          setCount(total);
          return list||[];
        }}
        onExpand={(e, payload) => {
          setRowKey([payload.id]);
          if (!e) return setRowKey([]);
          getChildren(payload);
        }}
        expandedRowKeys={rowKey}
        expandable={{ expandedRowRender }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      ></ProTable>

      <CreateForm
        width={800}
        title={updateModalVisible ? '修改数据' : '新建数据'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.parentId = value.parentId ? value.parentId.value : '';
            updateModalVisible ? (value.id = stepFormValues.id) : null;
            const success = updateModalVisible ? await handleUpdate(value) : await handleAdd(value);

            if (success) {
              handleModalVisible(false);
              handleUpdateModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updateModalVisible === true ? stepFormValues : '',
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 6 },
            wrapperCol: { span: 20 },
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
